package com.my.swas.photo.utils;

import cn.hutool.core.io.FileUtil;
import com.baidu.aip.imageprocess.AipImageProcess;
import com.my.swas.photo.config.YamlConfigUtil;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description:
 * @author: :MaYong
 */
@Slf4j
public class BaiDuImageProcessUtil {
    private static Logger logger = LoggerFactory.getLogger(BaiDuBodyAnalysisUtil.class);

    private static String APP_ID = "17176280";
    private static String API_KEY = "4Q7p6cbh8xb1oTX4X2EK3D5C";
    private static String SECRET_KEY = "GQ0dq9DgmuQc1DxQxFMq64lGGA9aLP18";


    // 并发访问锁
    private static final ReentrantLock lock = new ReentrantLock();
    private static AipImageProcess aipImageProcessInstance = null;

    // 静态初始化
    static {
        if (aipImageProcessInstance == null) {
            init();
        }
    }

    public BaiDuImageProcessUtil() {
    }

    /**
     * @author MaYong
     */
    private static void init() {
        lock.lock();
        try {
            if (aipImageProcessInstance == null) {
                aipImageProcessInstance = new AipImageProcess(APP_ID, API_KEY, SECRET_KEY);
                aipImageProcessInstance.setConnectionTimeoutInMillis(3000);
                aipImageProcessInstance.setSocketTimeoutInMillis(60000);
                log.info("百度：AipImageProcess 接口初始化完毕");
            }
        } finally {
            lock.unlock();
        }
    }

    /**
     * 取得实例
     *
     * @return 配置文件实例
     */
    public static AipImageProcess getInstance() {
        if (aipImageProcessInstance == null) {
            init();
        }
        return aipImageProcessInstance;
    }

    /**
     * 图片美化
     *
     * @param imageUrl
     */
    public static Boolean prettifyImage(String imageUrl) {
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        JSONObject res;
        if (CommonUtil.isHttpUrl(imageUrl)) {
            byte[] bytes = CommonUtil.readFileStream(imageUrl);
            res = aipImageProcessInstance.contrastEnhance(bytes, options);
        } else {
            res = aipImageProcessInstance.contrastEnhance(imageUrl, options);
        }
        if (res.has("error_code")) {
            logger.info("图像优化异常,异常编号:{},异常信息：{}", res.get("error_code"), res.get("error_msg"));
            return false;
        }
        Boolean bool = CommonUtil.saveImage(res.getString("image"),"");
        if (!bool) {
            return false;
        }
        return true;
    }

    /**
     * 图片美化
     *
     * @param file
     */
    public static Boolean prettifyImage(File file,String tempdir) {
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<>();
        byte[] bytes = CommonUtil.readFileStream(file);
        JSONObject res = aipImageProcessInstance.contrastEnhance(bytes,options);
        if (res.has("error_code")) {
            logger.info("图像优化异常,异常编号:{},异常信息：{}", res.get("error_code"), res.get("error_msg"));
            return false;
        }
        String tempPath = tempdir+File.separator+FileUtil.mainName(file)+"."+ FileUtil.extName(file);
        Boolean bool = CommonUtil.saveImage(res.getString("image"),tempPath);
        if (!bool) {
            return false;
        }
        return true;
    }

    public static String toBig(File file,String tempdir) throws IOException {
        HashMap<String, String> options = new HashMap<>();
        byte[] bytes = CommonUtil.readFileStream(file);
        JSONObject res = aipImageProcessInstance.imageQualityEnhance(bytes,options);
        String base64;
        String tempPath = tempdir+File.separator+FileUtil.mainName(file)+"."+ FileUtil.extName(file);
        if(res.has("image")){
            base64 = res.getString("image");
            CommonUtil.saveImage(base64,tempPath);
        }
        return tempPath;
    }
}
